/**
 * @description 文件分类上传管理
 * 
 * @company www.palmxj.com
 * @datetime 2010-11-15 AM
 */
Ext.define('FileUploadManager', {
	extend : 'Ext.Window',
	layout : 'fit',
	title : '附件分类管理',
	xtype : 'fileupload',
	iconCls : 'menu-file',
	width : 790,
	minWidth : 750,
	height : 550,
	minHeight : 550,
	maximizable : true,
	border : false,
	modal : true,
	buttonAlign : 'center',

	initComponent : function() {
		var store = Ext.create('Ext.data.TreeStore', {
					proxy : {
						type : "ajax",
						url : __ctxPath
								+ '/system/treeGlobalType.do?catKey=ATTACHFILE_TYPE'
					},
					root : {
						text : 'Root',
						expanded : true
					}
				});
		var tbar = new Ext.Toolbar({
					items : [{
								xtype : 'button',
								iconCls : 'btn-refresh',
								text : '刷新',
								scope : this,
								handler : function() {
									this.treePanel.store.reload();
								}
							}, '-', {
								xtype : 'button',
								text : '展开',
								iconCls : 'btn-expand',
								scope : this,
								handler : function() {
									this.treePanel.expandAll();
								}
							}, '-', {
								xtype : 'button',
								text : '收起',
								iconCls : 'btn-collapse',
								scope : this,
								handler : function() {
									this.treePanel.collapseAll();
								}
							}]
				});
		this.treePanel = new Ext.tree.TreePanel({
					region : 'west',
					title : '附件分类',
					collapsible : true,
					autoScroll : true,
					split : true,
					width : 220,
					tbar : tbar,
					rootVisible : false,
					store : store,
					listeners : {
						'itemclick' : {
							fn : this.nodeClick,
							scope : this
						},
						'itemcontextmenu' : {
							fn : this.contextmenu,
							scope : this
						}
					}
				}); // end of this treePanel

		// 判断附件类型[是否为图片]
		var fileType = this.permitted_extensions;
		var imageYes = this.judgeImage(fileType); // 判断是否为图片
		if (imageYes) {
			this.treePanel.setTitle('图片分类');
		}

		// ##panel##//
		this.panel = new Ext.Panel({
					layout : 'border',
					height : 500,
					border : false,
					items : [this.treePanel]
				});

		var topbar = new Ext.Toolbar({
					items : [{
//								text : '上传',
//								iconCls : 'btn-upload',
//								handler : this.upLoadFile,
//								scope : this
//							}, '-', {
								text : '上传',
								iconCls : 'btn-upload',
								handler : this.flexUploadFile,
								scope : this
							}, {
								xtype : 'hidden',
								itemId : 'fileuploadManager_panel_isImg', // 保存上传文件的格式[是图片true]
								value : imageYes
							}, ' /', {
								xtype : 'label',
								itemId : 'fileuploadManager_status',
								text : '总分类'
							}, '', {
								xtype : 'hidden',
								itemId : 'fileuploadManager_statusId',
								value : ''
							}]
				});
		if (!imageYes) {// 列表展示附件
			this.gridPanel = new KE.GridPanel({
						itemId : 'fileUploadManagerGridPanel',
						region : 'center',
						tbar : topbar,
						url : __ctxPath + '/system/listFileAttach.do',
						fields : [{
									name : 'fileId',
									type : 'int'
								}, {
									name : 'fileName',
									mapping : 'fileName'
								}, 'ext', 'note', 'fileType', 'filePath',
								'createtime', 'totalBytes'],
						columns : [{
									header : 'fileId',
									dataIndex : 'fileId',
									hidden : true
								}, {
									header : '附件名称',
									dataIndex : 'fileName',
									width : 160
								}, {
									header : '上传时间',
									dataIndex : 'createtime',
									format : 'y-m-d',
									width : 100
								}, {
									header : '大小',
									dataIndex : 'note',
									width : 100
								}, {
									text : '管理',
									width : 50,
									xtype : 'actioncolumn',
									items : [{
										iconCls : 'btn-detail',
										tooltip : '查看',
										handler : function(grid, rowIndex,
												colIndex) {
											var record = grid.getStore()
													.getAt(rowIndex);
											FileAttachDetail
													.show(record.data.fileId);
										}
									}]
								}]
					});

			this.gridPanel.addListener('rowdblclick', function(grid, record) {
						FileAttachDetail.show(record.data.fileId);
					});
			this.panel.add(this.gridPanel); // 附件列表
		} else {// 图片附件
			// ///////////////##显示图片的dataView中相关组件##//////////////
			var imageStore = new Ext.data.Store({
						proxy : {
							type : 'ajax',
							url : __ctxPath
									+ '/system/listFileAttach.do?type=image',
							reader : {
								type : 'json',
								rootProperty : 'result',
								totalProperty : 'totalCounts'
							}
						},
						pageSize : 15,
						fields : ['fileId', 'fileName', 'filePath']
					});
			imageStore.load();
			var imgTpl = new Ext.XTemplate(
					'<tpl for=".">',
					'<div style="width:105px; height : 105px;" class="thumb-wrap" id="{fileId}">',
					'<img align="middle" src="'
							+ __ctxPath
							+ '/attachFiles/{filePath}" style="width:90px;height:90px;margin-left:7px;" title="{fileName}"/>',
					'<center><span style="margin-top:3px;">{fileName}</span><center>',
					'</div>', '</tpl>');

			this.dataView = new Ext.view.View({
						region : 'center',
						store : imageStore,
						tpl : imgTpl,
						multiSelect : true,
						overItemCls : 'x-view-over',
						itemSelector : 'div.thumb-wrap',
						bodyStyle : 'padding:4px',
						emptyText : '目前尚无记录',
						listeners : {
							'dblclick' : {
								fn : this.imageDbClick,
								scope : this
							}
						}
					}); // end of this dataView

			// 图片展示,添加显示数据组件
			this.gridPanel = new Ext.Panel({
						region : 'center',
						tbar : topbar,
						layout : 'fit',
						defaults : {
							anchor : '96%,96%'
						},
						items : this.dataView,
						bbar : new Ext.PagingToolbar({
									pageSize : 15,
									store : imageStore,
									displayInfo : true,
									displayMsg : '当前显示从{0}至{1}， 共{2}条记录',
									emptyMsg : "当前没有记录"
								})
					}); // end of this gridPanel

			this.panel.add(this.gridPanel); // 图片展示
		}

		// this.panel.doLayout();
		this.items = [this.panel];

		this.buttons = [{
					text : '确定',
					iconCls : 'btn-ok',
					scope : this,
					handler : this.submit
				}, {
					text : '取消',
					iconCls : 'btn-cancel',
					scope : this,
					handler : this.close
				}];

		this.callParent();
	},

	// 树右键菜单
	contextmenu : function(menutree, node, items, index, e) {
		e.preventDefault();
		e.stopEvent();
		// 只有私有的才可以，修改，删除操作
		if (node.data.isPublic == 'false' || node.data.id == '0') {
			this.selected = {
				id : node.data.id,
				text : node.data.text
			};
			// 创建右键菜单
			var treeMenu = new Ext.menu.Menu({
						items : []
					});
			// treeMenu.clearMons();
			treeMenu.add({
						text : '新增',
						iconCls : 'btn-add',
						handler : this.addNode,
						scope : this
					});
			if (node.id > 0) { // 总分类不能删除，和修改
				treeMenu.add({
							text : '修改',
							iconCls : 'btn-edit',
							handler : this.editNode,
							scope : this
						}, {
							text : '删除',
							iconCls : 'btn-del',
							handler : this.delNode,
							scope : this
						});
			}
			treeMenu.showAt(e.getXY());
		}
	},
	// 添加节点
	addNode : function() {
		var globalTypeTree = this.treePanel;
		var parentId = this.selected.id;
		var globalTypeForm = new GlobalTypeForm({
					parentId : parentId,
					catKey : 'ATTACHFILE_TYPE',
					callback : function() {
						globalTypeTree.store.reload();
					}
				});
		globalTypeForm.show();
	},
	// 编辑节点
	editNode : function() {
		if (this.selected != null && this.selected.id != null) {
			var proTypeId = this.selected.id;
			var globalTypeForm = new GlobalTypeForm({
						proTypeId : proTypeId,
						callback : function() {
							this.treePanel.store.reload();
						}
					});
			globalTypeForm.show();
		}
	},
	// 删除节点
	delNode : function() {
		if (this.selected != null && this.selected.id != null) {
			Ext.Msg.confirm('操作提示', '你确定删除该数据?', function(btn) {
				if (btn == 'yes') {
					Ext.Ajax.request({
						url : __ctxPath
								+ '/system/delChildrensGlobalType.do?proTypeId='
								+ selected.id,
						success : function(result, request) {
							var res = Ext.util.JSON.decode(result.responseText);
							if (res.success == false) {
								Ext.ux.Toast.msg('操作提示', res.message);
							} else {
								Ext.ux.Toast.msg('操作提示', '删除成功!');
							}
							this.treePanel.store.reload();
						},
						failure : function(result, request) {
						}
					});
				}
			});
		} else {
			Ext.ux.Toast.msg('请选择对应数据！', '操作提示');
		}
	},

	/**
	 * 查看详细信息
	 */
	showdetail : function(fileId) {
		FileAttachDetail.show(fileId);
	},

	/**
	 * 下载
	 */
	downLoad : function(fileId) {
		window.open(__ctxPath + "/file-downLoad?fileId=" + fileId);
	},

	/**
	 * 文件上传[flex版本]
	 */
	flexUploadFile : function() {
		var fileCat = this.gridPanel.down('toolbar')
				.getComponent('fileuploadManager_statusId').value;
		if (this.treePanel.getSelection().length == 0) {
			Ext.ux.Toast.msg('操作提示', '请先选择左侧树的分类！');
			return;
		}
		var node = this.treePanel.getSelection()[0].data;
		var proTypeId = 0;
		if (node != null && node.id > 0) {
			proTypeId = node.id;
		}
		if (fileCat != null && fileCat != '') {
			FlexUploadDialog.show(fileCat, proTypeId);
		} else {
			var callback = this.callback;
			FlexUploadDialog.show(this.file_cat, proTypeId);
		}

	},

	/**
	 * 文件上传
	 */
	upLoadFile : function() {
		var me = this;
		var callback = this.callback;
		var dialog = new Ext.ux.UploadDialog.Dialog({
					file_cat : this.file_cat,
					url : this.url,
					scope : this,
					callback : function(obj) {
						if (obj != null && obj.length > 0) {
							var isImg = me.gridPanel
									.down('toolbar')
									.getComponent('fileuploadManager_panel_isImg')
									.getValue();
							if (isImg != '' && isImg == 'true') { // 图片上传
								var store = me.dataView.getStore();
								store.reload({
											params : {
												start : 0,
												limit : 15
											}
										});
							} else { // 非图片上传,刷新
								var grid = me.gridPanel;
								if (grid != null) {
									grid.getStore().reload();
								}
							}
							if (callback != null) {
								callback.call(this, obj);
							}
						}
						me.close();
					}
				});
		dialog.show('queryWindow');
	},

	/**
	 * 确定
	 */
	submit : function() {
		if (this.dialog) {
			this.dialog.close();
		}
		var callback = this.callback;
		var isImg = this.gridPanel.down('toolbar')
				.getComponent('fileuploadManager_panel_isImg').getValue(); // 判断是否为图片

		var records = null;
		if (isImg != null && isImg == 'true') { // 上传image图片
			var dv = this.dataView;
			if (dv != null) {
				records = dv.getSelection();
			}
		} else {
			var gridPanel = this.gridPanel;
			records = gridPanel.getSelectionModel().getSelection();
		}
		var arr = new Array();
		if (records != null && records.length > 0) {
			for (var i = 0; i < records.length; i++) {
				arr.push(records[i].data);
			}
		}

		if (callback != null) {
			var scope = this.scope ? this.scope : this;
			callback.call(scope, arr);
		}
		this.close();
	},

	/**
	 * 节点单击事件
	 */
	nodeClick : function(view, node, items, index, e) {
		if (node != null) {
			var file_type = '';
			if (node.getDepth() > 1 && node.data.nodeKey != 'file-type') {
				file_type = node.data.nodeKey;
			}
			var nodeLabel = '';
			var nodeKey = '';
			node.bubble(function(node) {
						if (node.data.text != undefined
								&& node.data.text != 'Root') {
							if (node.data.text == '总分类') {
								nodeLabel = '  总分类/' + nodeLabel;
							} else {
								nodeLabel = node.data.text + '/' + nodeLabel;
								nodeKey = node.data.nodeKey + '/' + nodeKey;
							}
						}
					});
			nodeLabel = nodeLabel.substring(0, nodeLabel.length - 1);
			var toolbar = this.gridPanel.down('toolbar');
			toolbar.getComponent('fileuploadManager_status').setText(nodeLabel);
			nodeKey = nodeKey.substring(0, nodeKey.length - 1);
			// toolbar.getComponent('fileuploadManager_statusId').setValue(nodeKey);
			toolbar.getComponent('fileuploadManager_statusId')
					.setValue(file_type);
			var isImg = toolbar.getComponent('fileuploadManager_panel_isImg')
					.getValue(); // 判断是否为图片
			if (isImg != null && isImg == 'true') { // 图片
				var store = this.dataView.getStore();
				store.proxy.url = __ctxPath
						+ '/system/listFileAttach.do?type=image';
				store.load({
							params : {
								start : 0,
								limit : 15,
								type : 'image',
								fileType : file_type
							}
						});
			} else { // 非图片
				var store = this.gridPanel.getStore();
				store.proxy.url = __ctxPath + '/system/listFileAttach.do';
				store.load({
							params : {
								start : 0,
								limit : 25,
								type : 'file',
								fileType : file_type
							}
						});
			}
		}
	},

	/**
	 * Image图片双击事件，显示图片信息
	 */
	imageDbClick : function(self) {
		var nodes = self.dataView.getSelectedNodes();
		if (nodes != '' && nodes != null && nodes != 'undefined') {
			FileUploadImageDetailForm.show(nodes[0].id);
		}
	},

	/**
	 * @desription 判断是否为图片，true:图片
	 * @remark 图片格式:jpg|gif|jpeg|png|bmp|JPG|GIF|JPEG|PNG|BPM
	 */
	judgeImage : function(types) {
		// var type = this.permitted_extensions;
		// 图片格式:jpg|gif|jpeg|png|bmp|JPG|GIF|JPEG|PNG|BPM
		if (types != null && types != 'undefined') {
			for (var i = 0; i < types.length; i++) {
				var type = types[i].toLowerCase();
				if (type == 'bmp' || type == 'png' || type == 'jpeg'
						|| type == 'jpg' || type == 'tiff' || type == 'gif') { // 上传image图片
					return true;
				}
			}
		}
		return false;
	}
});
